/* eslint-disable no-const-assign,prefer-destructuring */
/**
 * Created by mar105 on 2019-01-04.
 */

import React, { Component } from 'react';
import { Layout, Form, Spin, Tabs, Avatar, message, Modal } from 'antd';
import CommonSales from './../Common/CommonBillEvent'; /* 继承销售模块业务功能 */
import * as commonFunc from './../Common/commonFunc'; /* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from './../Common/ToolBar/ToolBarNew';
import StaticEditTable from './../Common/CommonTable'; /* 可编辑表格 */
import styles from './../../index.less';
import CommonView from './../Common/CommonView';
import CommonBase from './../Common/CommonBase'; /* 获取配置及数据 */
import * as commonUtils from './../../utils/utils'; /* 通用方法 */
import * as commonBusiness from './../Common/commonBusiness'; /* 单据业务功能 */
import * as commonConfig from './../../utils/config';
import * as commonServices from './../../services/services'; /*   服务类   */


const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { confirm } = Modal;

class WorkOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentWillReceiveProps(nextProps) {
    let {
      employeeColumn,
    } = nextProps;
    const { formData } = nextProps;
    if (commonUtils.isEmptyArr(employeeColumn) && formData.length > 0) {
      const employeeConfig = formData.filter(item => item.sTbName.toUpperCase() === 'mftproductionreportemployee'.toUpperCase())[0];
      employeeColumn = commonFunc.getHeaderConfig(employeeConfig, employeeColumn);
      this.handleGetData(employeeConfig);
      this.props.onSaveState({
        employeeConfig, employeeColumn,
      });
    }
  }

  shouldComponentUpdate(nextProps) {
    const { employeeColumn, slaveConfig } = nextProps;
    return Object.keys(slaveConfig).length > 0 && commonUtils.isNotEmptyArr(employeeColumn);
  }

  /* 获取表数据 */
  handleGetData = (employeeConfig) => {
    const { currentId } = this.props; /* 当前页签数据 */
    const sId = currentId !== undefined ? currentId : ''; /* 数据Id */
    this.props.handleGetDataSet({
      name: 'employee', configData: employeeConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.onSaveState({ pageLoading: false });
  };

  handleForm = (form) => {
    this.form = form;
  };

  handleSave = () => {
    this.form.validateFieldsAndScroll(async (err) => {
      /*   验证通过与不通过走不同的流程   */
      if (err) { /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const key of Object.keys(err)) {
          message.warning(err[key].errors[0].message);
        }
      } else { /*   验证成功   */
        const {
          masterConfig, masterData, slaveConfig, slaveData, slaveDelData, employeeConfig, employeeData, employeeDelData,
        } = this.props;
        if (!commonBusiness.validateTable(slaveConfig, slaveData) || !commonBusiness.validateTable(employeeConfig, employeeData)) {
          return;
        }

        const data = [];
        data.push(commonBusiness.mergeData('master', masterConfig.sTbName, [masterData]));
        data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
        data.push(commonBusiness.mergeData('employee', employeeConfig.sTbName, employeeData, employeeDelData));
        await this.props.onSaveData({ data, sClientType: '1' });
        this.handleGetData(employeeConfig);
      }
    });
  };

  /** 控制选择控制表时，显示部件工序与成品工序 */
  handleFilterData = (name, dataIndex, value, record) => {
    return (commonUtils.isNotEmptyStr(record.sSlaveId) && record.sSlaveId.toString().toLowerCase().includes(value.toLowerCase()));
  };

  /**   添加表格空行   */
  handleTableAdd = async (name) => {
    /*   外置处理业务   */
    const {
      slaveData, slaveSelectedRowKeys, sModelsId, token,
    } = this.props;
    let {
      employeeData,
    } = this.props;
    if (name === 'employee') {
      if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) {
        message.warn('请选择班组');
        return;
      }
      if (slaveSelectedRowKeys.length !== 1) {
        message.warn('请选择一条数据');
        return;
      }
      const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
      if (iIndex > -1) {
        if (commonUtils.isEmpty(slaveData[iIndex].sTeamName)) {
          message.warn('班组名称不能为空');
          return;
        }
      }
      const employeeSlaveData = employeeData.filter(item => item.sSlaveId === slaveSelectedRowKeys[0]);
      if (commonUtils.isEmptyObject(employeeSlaveData)) {
        const sTeamId = slaveData[iIndex].sTeamId;
        const sSlaveId = slaveData[iIndex].sId;
        const sParentId = slaveData[iIndex].sParentId;
        const url = `${commonConfig.server_host}eleteamemployee/getEleteamemployee?sModelsId=${sModelsId}&sTeamId=${sTeamId}&sSlaveId=${sSlaveId}&sParentId=${sParentId}`;
        const dataReturn = (await commonServices.getService(token, url)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows;
          returnData.forEach((child) => {
            employeeSlaveData.push({
              sId: child.sId,
              sParentId: child.sParentId,
              sSlaveId: child.sSlaveId,
              sEmployeeId: child.sEmployeeId,
              handleType: 'add',
            });
          });
        }
        employeeData = employeeData.concat(employeeSlaveData);
        this.props.onSaveState({ [`${name}Data`]: employeeData });
      } else {
        const employeeSlaveDataAdd = {};
        employeeSlaveDataAdd.sId = commonUtils.createSid();
        employeeSlaveDataAdd.sParentId = slaveData[iIndex].sParentId;
        employeeSlaveDataAdd.sSlaveId = slaveData[iIndex].sId;
        employeeSlaveDataAdd.handleType = 'add';
        employeeData = employeeData.concat(employeeSlaveDataAdd);
        this.props.onSaveState({ [`${name}Data`]: employeeData });
      }
    } else {
      this.props.onDataRowAdd(name);
    }
  };
  /**   删除表格数据   */
  otherTableDel = (name, tableSelectedRowKeys) => {
    const tableData = this.props[`${name}Data`];
    let tableDelData = this.props[`${name}DelData`];
    tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData;
    for (const sId of tableSelectedRowKeys) {
      /*   看看删除集合和从表中是否都存在该条数据   */
      let tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      while (tableDataIndex > -1) {
        /*   删除从表中的数据并存入删除集合中   */
        const slaveDataFilter = tableData[tableDataIndex];
        tableData.splice(tableDataIndex, 1);
        slaveDataFilter.handleType = 'del';
        tableDelData.push(slaveDataFilter);
        tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      }
    }
    return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] };
  };
  /**   删除表格数据   */
  handleTableDel = (name) => {
    if (name === 'control') {
      const tableSelectedRowKeys = this.props[`${name}SelectedRowKeys`];
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        const materialsReturnData = this.otherTableDel('materials', tableSelectedRowKeys);
        const processReturnData = this.otherTableDel('process', tableSelectedRowKeys);
        const controlReturnData = this.props.onDataRowDel(name, true);
        this.props.onSaveState({
          ...materialsReturnData,
          ...processReturnData,
          ...controlReturnData,
        });
        return true;
      } else {
        return false;
      }
    } else {
      return this.props.onDataRowDel(name);
    }
  };

  /*  上一条、下一条、首条、末条 */
  handleSearchData = async (handleType) => {
    const {
      employeeConfig,
    } = this.props;
    const bReturn = await this.props.onSearchData(handleType);
    if (bReturn) {
      this.handleGetData(employeeConfig);
    }
  };
  handleEdit = () => {
    const { employeeConfig } = this.props;
    this.props.onEdit();
    this.handleGetData(employeeConfig);
  };
  /**   获取主表、从表、审核表、员工表数据   */
  handleGetTableData = (masterConfig, slaveConfig, checkConfig, employeeConfig) => {
    const { currentId } = this.props; /* 当前页签数据 */
    const sId = currentId !== undefined ? currentId : '';
    this.props.handleGetDataOne({
      name: 'master', configData: masterConfig, condition: { sId, pageSize: '', pageNum: '' },
    });
    this.props.handleGetDataSet({
      name: 'slave', configData: slaveConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.handleGetDataSet({
      name: 'check', configData: checkConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.handleGetDataSet({
      name: 'employee', configData: employeeConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
  };
  /*   取消操作  */
  handleCancel = (obj) => {
    /*   待用数据声明   */
    const {
      masterConfig, slaveConfig, checkConfig, employeeConfig,
    } = this.props;
    const onGetDataOk = this.handleGetTableData;
    const onSaveStateOk = this.props.onSaveState;
    confirm({
      title: obj.title,
      onOk() {
        onGetDataOk(masterConfig, slaveConfig, checkConfig, employeeConfig);
        onSaveStateOk({ enabled: false });
      },
      onCancel() {
      },
    });
  };
  /**  点击新增按钮   */
  handleAdd = (config, copyTo) => {
    let configNew = {};
    if (commonUtils.isEmptyObject(config)) {
      const { masterConfig, slaveConfig } = this.props;
      configNew.masterConfig = masterConfig;
      configNew.slaveConfig = slaveConfig;
    } else {
      configNew = config;
    }
    const state = this.props.onAdd(configNew, copyTo, true);
    const { masterData, slaveData } = state;
    const employeeData = [];
    if (commonUtils.isNotEmptyObject(copyTo)) {
      const copyToControlConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.employee`.toLowerCase());
      const employeeAssignField = commonUtils.isNotEmptyArr(copyToControlConfig) ? copyToControlConfig[0].sAssignField : '';

      const newCopyTo = {};
      newCopyTo.masterData = copyTo.masterData;
      newCopyTo.slaveData = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
      copyTo.employeeData.forEach((employeeItem) => {
        newCopyTo.employeeData = employeeItem;
        let employeeRow = commonFunc.getDefaultData(config.employeeConfig, newCopyTo); // 取默认值
        employeeRow = { ...employeeRow, ...commonFunc.getAssignFieldValue(employeeAssignField, employeeItem, newCopyTo) }; // 取赋值字段
        employeeRow.handleType = 'add';
        employeeRow.sId = commonUtils.createSid();
        employeeRow.sParentId = masterData.sId;
        employeeData.push(employeeRow);
      });
    }
    const stateNew = {
      ...state,
      employeeData,
      employeeSelectedRowKeys: [],
    };
    this.props.onSaveState(stateNew);
  };
  /* 非列表联动下拉 */
  handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const {
      masterData, masterConfig, sModelsId, app,
    } = this.props;
    const { token } = app;
    let { sBackProcessClassifyData } = this.props;

    let { sAllPartsName } = masterData;
    if (sFieldName === 'sProductId') {
      await this.handleBackProcessData();
      let allPartsName = [];
      if (sAllPartsName !== undefined) {
        allPartsName = sAllPartsName.split(',');
      }

      if (allPartsName.length > 0 && masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length > 0 &&
        (sBackProcessClassifyData !== undefined && sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length > 0)) {
        let iIndex;
        allPartsName.forEach((sPartsName) => {
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `dSumPQty${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `sMaterialsName${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPrintModePo${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPositiveColor${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }

          if (sBackProcessClassifyData !== '') {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
              iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId + sPartsName);
              if (iIndex > -1) {
                masterConfig.gdsconfigformslave.splice(iIndex, 1);
              }
            });
          }
        });
        if (sBackProcessClassifyData !== '') {
          sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
            iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId);
            if (iIndex > -1) {
              masterConfig.gdsconfigformslave.splice(iIndex, 1);
            }
          });
        }
      }


      let sProductClassifyId;
      if (changeValue !== null && changeValue !== undefined) {
        sProductClassifyId = changeValue.sProductClassifyId;
        sAllPartsName = changeValue.sAllPartsName;
      } else {
        sProductClassifyId = masterData.sProductClassifyId;
      }
      if (commonUtils.isEmpty(sProductClassifyId)) {
        return;
      }
      const sBackProcessClassify = masterConfig.gdsconfigformslave.filter(item => (item.sName.toLowerCase() === 'sbackprocessclassify'))[0];

      const values = { sKeyUpFilterName: '', sSqlCondition: { sProductClassifyId } };
      const dataReturn = (await commonServices.postValueService(token, values, `${commonConfig.server_host}business/getSelectDataBysControlId/${sBackProcessClassify.sId}?sModelsId=${sModelsId}`)).data;
      /*   接收返回值   */
      /*   成功的话刷新页面(同步主表和从表数据),不成功就弹出错误提示   */
      if (dataReturn.code === 1) { /*   成功   */
        const { rows } = dataReturn.dataset;

        allPartsName = [];
        if (sAllPartsName !== undefined) {
          allPartsName = sAllPartsName.split(',');
        }

        sBackProcessClassifyData = rows;
        if (allPartsName.length > 0 && masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length <= 0 &&
          sBackProcessClassifyData !== undefined && sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length <= 0) {
          const sumPQtyConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'dSumPQty').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'dSumPQty')[0] : [];
          const materialsNameConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'sMaterialsName').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'sMaterialsName')[0] : [];
          const printModePoConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPrintModePo').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPrintModePo')[0] : [];
          const positiveColorConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPositiveColor').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPositiveColor')[0] : [];
          const processNameConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'sProcessName').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'sProcessName')[0] : [];

          let ConfigNew;
          allPartsName.forEach((item) => {
            ConfigNew = { ...sumPQtyConfig };
            ConfigNew.sName = `dSumPQty${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...materialsNameConfig };
            ConfigNew.sName = `sMaterialsName${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...printModePoConfig };
            ConfigNew.sName = `iPrintModePo${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...positiveColorConfig };
            ConfigNew.sName = `iPositiveColor${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);
            if (sBackProcessClassifyData !== '') {
              sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
                ConfigNew = { ...processNameConfig };
                ConfigNew.sName = processClassify.sId + item;
                masterConfig.gdsconfigformslave.push(ConfigNew);
              });
            }
          });
          if (sBackProcessClassifyData !== '') {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
              ConfigNew = { ...processNameConfig };
              ConfigNew.sName = processClassify.sId;
              masterConfig.gdsconfigformslave.push(ConfigNew);
            });
          }
        }
        const returnChange = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
        this.props.onSaveState({ ...returnChange, sBackProcessClassifyData, masterConfig });
      } else { /*   失败   */
        message.error(dataReturn.msg);
      }
    } else {
      this.props.onChange(name, sFieldName, changeValue, sId, dropDownData);
    }
  };
  handleDel = (obj) => {
    const props = { ...this.props, ...this.state };
    const onOkDel = this.handleOkDel;
    confirm({
      title: obj.title,
      onOk() {
        onOkDel(props);
      },
      onCancel() {
      },
    });
  };
  handleOkDel = async (props) => {
    /*   数据参数   */
    const {
      token, sModelsId, masterConfig, masterData, slaveConfig, checkConfig, employeeConfig,
    } = props;
    const value = {
      sClientType: '1',
      data: {
        sMasterTable: masterConfig.sTbName,
        sId: [masterData.sId],
        sSlaveTable: [
          {
            tableName: slaveConfig.sTbName,
            relationName: 'sParentId',
          }, {
            tableName: checkConfig.sTbName,
            relationName: 'sBillId',
          }, {
            tableName: employeeConfig.sTbName,
            relationName: 'sParentId',
          }],
      },
    };
    const url = `${commonConfig.server_host}business/delMasSlaBusinessData?sModelsId=${sModelsId}`;
    /*   接收返回值   */
    const { data } = await commonServices.postValueService(token, value, url);
    if (data.code === 1) {
      /*   数据删除成功   */
      if (this.props.app.currentPane.refresh !== undefined) {
        this.props.app.currentPane.refresh();
      }
      this.handleDelDataSuccess(props);
    } else { /*   失败   */
      this.props.getServiceError(data);
    }
  };
  /* 数据删除成功跳转到新路由即pane */
  handleDelDataSuccess = (props) => {
    const { app } = props;
    let { panes, currentPane } = app;
    /* 删除单据后退出当前路由后,标签panes变化后的集合 */
    panes = panes.filter(pane => pane.key !== currentPane.key);
    /* 跳转到panes集合的最后一个路由，因为panes集合一定含有主页路由所以panes的集合大于等于1 */
    currentPane = panes[panes.length - 1];
    this.props.onRemovePane(panes, currentPane);
  };
  render() {
    const { pageLoading, masterData } = this.props;
    const imgSrc = commonBusiness.handleAddIcon(masterData);
    return (
      <Spin spinning={pageLoading}>
        <WorkOrderComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onSubmit={this.handleSave}
          onFilterData={this.handleFilterData}
          onDataRowAdd={this.handleTableAdd}
          onDataRowDel={this.handleTableDel}
          onNext={this.handleSearchData.bind(this, 'next')}
          onBtnPrior={this.handleSearchData.bind(this, 'up')}
          onBtnFirst={this.handleSearchData.bind(this, 'first')}
          onBtnLast={this.handleSearchData.bind(this, 'end')}
          onEdit={this.handleEdit}
          onDel={this.handleDel}
          onCancel={this.handleCancel}
          onAdd={this.handleAdd}
          onMasterChange={this.handleMasterChange}
          imgSrc={imgSrc}
        />
      </Spin>
    );
  }
}

const WorkOrderComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const { form, onReturnForm } = props;
  /*   回带表单   */
  onReturnForm(form);
  const propsType = {
    ...props,
    onChange: props.onMasterChange,
  };
  const employeePropsType = {
    ...commonBusiness.getTableTypes('employee', props),
    filteredValue: props.slaveSelectedRowKeys,
    onFilterData: props.onFilterData,
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar {...props} />
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <CommonView {...propsType} />
            <div id="slaveTabs" className={styles.bShow}>
              <div>
                <Avatar src={props.imgSrc} />
              </div>
              <Tabs className={styles.slaveTabs}>
                <TabPane tab="主体内容" key={2}>
                  <StaticEditTable {...commonBusiness.getTableTypes('slave', props)} />
                </TabPane>
                <TabPane tab="审批信息" key={3}>
                  <StaticEditTable {...commonBusiness.getTableTypes('check', props)} />
                </TabPane>
              </Tabs>
            </div>
            <StaticEditTable {...employeePropsType} />
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonSales(WorkOrder));
